<template>
  <div class="page-content">
    <div class="header">
      <h3>套餐等级管理</h3>
    </div>

    <div class="filter-bar">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索等级名称..."
            clearable
            @clear="fetchVipLevels()"
            @keyup.enter="fetchVipLevels()"
          >
            <template #append>
              <el-button @click="fetchVipLevels()">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="12" class="action-buttons">
          <el-button type="primary" @click="openAddDialog" v-ripple>添加套餐等级</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table
      v-loading="loading"
      :data="filteredVipLevels"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="vip_name" label="等级名称" />
      <el-table-column prop="level" label="等级值" width="100" />
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column prop="updated_at" label="更新时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="editVipLevel(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="deleteVipLevel(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑套餐等级' : '添加套餐等级'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="vipFormRef"
        :model="vipForm"
        :rules="vipRules"
        label-width="100px"
      >
        <el-form-item label="等级名称" prop="vip_name">
          <el-input v-model="vipForm.vip_name" placeholder="请输入套餐等级名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveVipLevel">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { 
  getVipLevels, 
  addVipLevel, 
  updateVipLevel, 
  deleteVipLevelById
} from '@/Newapi/device'

// 接口类型定义
interface VipLevel {
  id: number
  created_at: string
  updated_at: string
  vip_name: string
  level: number
}

// 状态变量
const loading = ref(false)
const vipLevels = ref<VipLevel[]>([])
const searchKeyword = ref('')

// 过滤后的VIP等级列表
const filteredVipLevels = computed(() => {
  if (!searchKeyword.value) return vipLevels.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return vipLevels.value.filter(
    item => item.vip_name.toLowerCase().includes(keyword)
  )
})

// 表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const vipFormRef = ref<FormInstance>()
const vipForm = reactive({
  id: 0,
  vip_name: ''
})
const vipRules = {
  vip_name: [
    { required: true, message: '请输入套餐等级名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符之间', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  fetchVipLevels()
})

// 获取套餐等级列表
const fetchVipLevels = async () => {
  loading.value = true
  try {
    const res = await getVipLevels()
    
    if (res.code === 200) {
      vipLevels.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取套餐等级列表失败')
    }
  } catch (error) {
    console.error('获取套餐等级列表失败:', error)
    ElMessage.error('获取套餐等级列表失败')
  } finally {
    loading.value = false
  }
}

// 打开添加对话框
const openAddDialog = () => {
  isEdit.value = false
  vipForm.id = 0
  vipForm.vip_name = ''
  dialogVisible.value = true
}

// 编辑套餐等级
const editVipLevel = (row: VipLevel) => {
  isEdit.value = true
  vipForm.id = row.id
  vipForm.vip_name = row.vip_name
  dialogVisible.value = true
}

// 删除套餐等级
const deleteVipLevel = (row: VipLevel) => {
  ElMessageBox.confirm(`确定要删除套餐等级 "${row.vip_name}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      const res = await deleteVipLevelById(row.id)
      
      if (res.code === 200) {
        ElMessage.success('套餐等级已删除')
        fetchVipLevels()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除套餐等级出错:', error)
      ElMessage.error('删除失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 保存套餐等级
const saveVipLevel = async () => {
  if (!vipFormRef.value) return
  
  await vipFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        
        let res
        if (isEdit.value) {
          // 更新套餐等级
          res = await updateVipLevel({
            id: vipForm.id,
            vip_name: vipForm.vip_name
          })
        } else {
          // 添加套餐等级
          res = await addVipLevel({
            vip_name: vipForm.vip_name,
            level: 0 // 默认传0
          })
        }
        
        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '套餐等级已更新' : '套餐等级已添加')
          dialogVisible.value = false
          fetchVipLevels()
        } else {
          ElMessage.error(res.msg || (isEdit.value ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '更新套餐等级出错:' : '添加套餐等级出错:', error)
        ElMessage.error('操作失败，请重试')
      } finally {
        loading.value = false
      }
    } else {
      return false
    }
  })
}
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid var(--art-border-color);

    h3 {
      font-size: 18px;
      font-weight: 500;
    }
  }

  .filter-bar {
    margin: 20px 0;
    
    .action-buttons {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
  }
}
</style> 